package com.guigutool.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guigutool.reggie.common.BaseContext;
import com.guigutool.reggie.common.R;
import com.guigutool.reggie.entity.AddressBook;
import com.guigutool.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Author: KingWang
 * @Date: 2023/3/15
 * @Desc:
 **/
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("addressBook:{}", addressBook);
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
        log.info("addressBook:{}",addressBook);
        addressBookService.setDefault(addressBook);
        return R.success(addressBook);
    }


    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        wrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(wrapper);
        if(Objects.nonNull(addressBook)){
            return R.success(addressBook);
        }
        return R.error("未设置默认地址");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        addressBook.setUserId(BaseContext.getCurrentId());
        wrapper.eq(Objects.nonNull(addressBook),AddressBook::getUserId,addressBook.getUserId());
        wrapper.orderByDesc(AddressBook::getUpdateTime);
        return R.success(addressBookService.list(wrapper));
    }
}
